package com.question_barrier.controller;

import com.question_barrier.entity.Barrier;
import com.question_barrier.entity.BarrierState;
import com.question_barrier.entity.User;
import com.question_barrier.result.ResultModel;
import com.question_barrier.result.StateCode;
import com.question_barrier.service.*;
import com.question_barrier.utils.SnowflakeIdWorker;
import com.question_barrier.vo.barrier.BarrierInfo;
import com.question_barrier.vo.question.Answers;
import com.question_barrier.vo.question.Question;
import com.question_barrier.vo.question.QuestionDetail;
import com.question_barrier.vo.question.TagsDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/barrier")
@Api(value = "关卡模块", description = "关卡模块接口信息")
public class BarrierController {
    @Autowired
    BarrierService barrierService;
    @Autowired
    UserService userService;
    @Autowired
    BarrierStateService barrierStateService;
    @Autowired
    QuestionBankService questionBankService;
    @Value("${question-bank-api.get-question-url}")
    private String getQuestionUrl;
    @Value("${question-bank-api.get-answer-url}")
    private String getAnswerUrl;
    @Value("${question-bank-api.get-all-tags-url}")
    private String getAllTagsUrl;
    SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);

    @RequestMapping(value = "/getAllBarrier",method = RequestMethod.GET)
    @ApiOperation(value = "获取所有关卡信息")
    public ResultModel getAllBarrier(){
        ResultModel resultModel = new ResultModel();
        List<Barrier> barrierList = barrierService.getAllBarrier();
        resultModel.setCode(StateCode.REQUESTSUCCESS);
        resultModel.chooseMsg();
        resultModel.setData(barrierList);
        return resultModel;
    }

    @RequestMapping(value = "/getBarrier",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "用户openId", required = true, paramType = "query"),
            @ApiImplicitParam(name = "subject", value = "科目", required = true, paramType = "query"),
            @ApiImplicitParam(name = "grade", value = "年级", required = true, paramType = "query"),
    })
    @ApiOperation(value = "获取用户关卡信息", notes = "根据年级和科目，返回总关卡数和用户的最新关卡")
    public ResultModel<BarrierInfo> getBarrier(String openId, String grade, String subject){
        ResultModel resultModel = new ResultModel();
        //User user = userService.findByOpenId(openId);
        long totalBarriers = 0;
        List<Barrier> barrierList  = barrierService.findByGradeAndSubject(grade,subject);
        if(barrierList.size() > 0)
            totalBarriers = barrierList.size();
        if(barrierStateService.existsByOpenIdAndGradeAndSubject(openId,grade,subject)) {
            BarrierState barrierState = barrierStateService.findByOpenIdAndGradeAndSubject(openId, grade, subject);
            long latestBarrierId = barrierState.getLatestBarrierId();
            Barrier barrier = barrierService.findById(latestBarrierId);
            BarrierInfo barrierInfo = new BarrierInfo(totalBarriers, barrier.getDegree());
            resultModel.setData(barrierInfo);
        }else {
            long id = idWorker.nextId();
            long integral = 0;
            Date date = new Date();
            byte isDel = 0;
            Barrier barrier = barrierService.findByGradeAndSubjectAndDegree(grade, subject, 1);
            BarrierState barrierState = new BarrierState(id, openId, grade, subject, barrier.getId(), date, openId, date, openId, isDel);
            barrierStateService.updBarrierState(barrierState);
            BarrierInfo barrierInfo = new BarrierInfo(totalBarriers, barrier.getDegree());
            resultModel.setData(barrierInfo);
        }
        resultModel.setCode(StateCode.FINDSUCCESS);
        resultModel.chooseMsg();
        return  resultModel;
    }

    @RequestMapping(value = "/getQuestion",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grade", value = "年级", required = true, paramType = "query"),
            @ApiImplicitParam(name = "subject", value = "科目", required = true, paramType = "query"),
            @ApiImplicitParam(name = "degree", value = "关卡号", required = true, paramType = "query"),
    })
    @ApiOperation(value = "获取关卡题目",notes = "根据年级，科目和关卡号，返回题目")
    public ResultModel<List<Question>> getQuestion(String grade,String subject,Long degree){
            ResultModel resultModel = new ResultModel();
           if(barrierService.existsByGradeAndSubjectAndDegree(grade,subject,degree)){
                Barrier barrier = barrierService.findByGradeAndSubjectAndDegree(grade,subject,degree);
                long questionQuantity = barrier.getQuestionQuantity();
                TagsDetail tagsDetail = questionBankService.getAllTags(getAllTagsUrl);
                List<String> tagIdList = new ArrayList<String>();
                for(int i=0;i<tagsDetail.getData().size();i++){
                    for(int j=0;j<tagsDetail.getData().get(i).getChildren().size();j++){
                        if("单选题".equals(tagsDetail.getData().get(i).getChildren().get(j).getTagValue()) ||
                                //barrier.getDifficulty().equals(tagsDetail.getData().get(i).getChildren().get(j).getTagValue()) ||
                                //grade.equals(tagsDetail.getData().get(i).getChildren().get(j).getTagValue()) ||
                                subject.equals(tagsDetail.getData().get(i).getChildren().get(j).getTagValue())){
                            tagIdList.add(tagsDetail.getData().get(i).getChildren().get(j).getTagId());
                            break;
                        }
                    }
                }
                QuestionDetail questionDetail = questionBankService.getQuestion(Long.toString(questionQuantity), tagIdList,getQuestionUrl);
                if(questionDetail.getData().size() > 0){
                    List<Question> questionList = new ArrayList<Question>();
                    Answers answers ;
                    for(int i=0;i< questionDetail.getData().size();i++){
                        answers = questionBankService.getAnswers(questionDetail.getData().get(i).getTopic().getId(), getAnswerUrl);
                        questionList.add(new Question(questionDetail.getData().get(i), answers));
                    }
                    resultModel.setCode(StateCode.FINDSUCCESS);
                    resultModel.chooseMsg();
                    resultModel.setData(questionList);
                }else{
                    resultModel.setCode(StateCode.FINDFAIL);
                    resultModel.chooseMsg();
                }

           }else {
               resultModel.setCode(StateCode.FINDFAIL);
               resultModel.chooseMsg();
           }
           return resultModel;
    }



    //@RequestMapping(value = "/addBarrier",method = RequestMethod.POST)
    public ResultModel addBarrier(){
        long id = idWorker.nextId();
        List<String> grades = new ArrayList<>();
        grades.add("一年级");grades.add("二年级");grades.add("三年级");grades.add("四年级");grades.add("五年级");grades.add("六年级");
        List<String> subjects = new ArrayList<>();
        subjects.add("语文");subjects.add("数学");subjects.add("英语");
        long limitedTime = 60;
        Date date = new Date();
        byte isDel =0;
        List<String> difficulties = new ArrayList<>();
        long[] questionCount = new long[]{-1,5,5,5,5,6,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10};
        difficulties.add("简单"); difficulties.add("中等"); difficulties.add("困难");
        for(int i=0;i<grades.size();i++){
            for(int j=0;j<subjects.size();j++){
                for(int degree=1;degree<=20;degree++){
                    if(degree<=7){
                        Barrier barrier = new Barrier(idWorker.nextId(), grades.get(i), subjects.get(j), difficulties.get(0), degree, questionCount[degree], limitedTime, date, id, date, id, isDel);
                        barrierService.addBarrier(barrier);
                    }else{
                        if(degree <= 14){
                            Barrier barrier = new Barrier(idWorker.nextId(), grades.get(i), subjects.get(j), difficulties.get(1), degree, questionCount[degree], limitedTime, date, id, date, id, isDel);
                            barrierService.addBarrier(barrier);
                        }else{
                            Barrier barrier = new Barrier(idWorker.nextId(), grades.get(i), subjects.get(j), difficulties.get(2), degree, questionCount[degree], limitedTime, date, id, date, id, isDel);
                            barrierService.addBarrier(barrier);
                        }
                    }
                }
            }
        }
        return new ResultModel();
    }

}
